package com.cnspt.controllers;

import com.alibaba.fastjson.JSONObject;
import com.cnspt.utils.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@Controller
@RequestMapping("index")
@CrossOrigin(originPatterns = "*", methods = {RequestMethod.GET, RequestMethod.POST})
public class IndexController {
    @RequestMapping("index" )
    public String index() {
        return "index/index";
    }

    @RequestMapping(value = "showpdf", method = RequestMethod.GET)
    public void showpdf(HttpServletRequest req, HttpServletResponse res) {
        String fileName = "浪潮软件股份有限公司.pdf";
        try {
            Download.breakpoint(fileName, req, res);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    @Value("${pdf.path}")
    public String path;

    @Value("${pdf.newPath}")
    public String newPath;

    @ResponseBody
    @RequestMapping(value="rsa", method = RequestMethod.GET)
    public String rsa(String str) throws Exception {
        System.out.println(str);
//        String str = MD5Util.getMD5("{\"CLD_HEADER\":{\"CLD_TX_CHNL\":\"YSTEST\",\"CLD_TX_TIME\":\"20191112145911\",\"CLD_TX_CODE\":\"svc_userRegister\",\"CLD_TX_SEQ\":\"\"},\"CLD_BODY\":{\"USER_ID\":\"user123\",\"ORDER_ID\":\"order123\",\"ORDER_DT\":\"20191112145811\",\"TOTAL_AMT\":\"100.00\",\"PAY_AMT\":\"90.00\",\"DISCOUNT_AMT\":\"10.00\",\"ORDER_STATUS\":\"1\",\"REFUND_STATUS\":\"0\",\"MCT_NM\":\"XXX商户\"}}");
//        System.out.println(str);


        // 公钥
        String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDC+8V1Or6R6H3a7TjuvoDa5k0W/niEGg4N+0Nni+KfwHVX05pI7Qdq1J5+q31yORAoiSSNZNW4uWykmeSltC2mHGkQXClU4JmMXnWFyRCENw1iDIIIEsNax4jFBZUaDCn69PxWgp5wwk+d0V7QRYZ9jkgUaJK+BSYa0KMraxVfJwIDAQAB";

        // 私钥
        String privateKey = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAML7xXU6vpHofdrtOO6+gNrmTRb+eIQaDg37Q2eL4p/AdVfTmkjtB2rUnn6rfXI5ECiJJI1k1bi5bKSZ5KW0LaYcaRBcKVTgmYxedYXJEIQ3DWIMgggSw1rHiMUFlRoMKfr0/FaCnnDCT53RXtBFhn2OSBRokr4FJhrQoytrFV8nAgMBAAECgYEAizhN0thw/altQ4YiIoWvZ50M6iAkWN5prp37kNGWrM40etNB1FQ5+ZN636L+3THVUbwqdzLKTy1GX3jqg05VUIf0sKYYepp+skwZmHVprz4EUKsZXRa+3MnMChJcyHdlyuUNs6HriMq6Qc1+fFEOtZFAf3lo2wYNFw5vIKHGQRECQQDxVKa+6m4y7LmWgiGLYghuL/SGXySFhwBh5+zMNl8V7aAbTX/tH6A0s8JXsSI4iChjWPXthKFTrd7h62vJBjeFAkEAztXpNehF18g3e6JEhtjbTmMsgyj13gdSZSRwjO0Y+IsDI1afnZXzwv96OlukGK8185z0bsbhTCOd6rkcRTnduwJBAOqGknlMh4VTylO66PB0d67lSaPgCDT/al67LcOTPzqnMAX4fc6qAl3VJ5Ni39fCckWB6ZVGZCVW/hfdWmUEdqUCQFFWNXuJd82/YnIwAZq1tKhCv8JkXSuO3YwApHIG2wcCQ52l9ubVjSJlrP8+Am3imOjQFB9r/jUe3H7thHyEoPkCQCay3waa0ll2DY+epkrrF/QO7aMa6NIUArRgWUmqw+1/45csBiWPMUrAD/CPDUr9Jvte92NjoAlz649csbgMM3w=";

        // 源报文(未加密)
        String msg = "{\"CLD_HEADER\":{\"CLD_TX_CHNL\":\"YSTEST\",\"CLD_TX_TIME\":\"20191112145911\",\"CLD_TX_CODE\":\"svc_userRegister\",\"CLD_TX_SEQ\":\"\"},\"CLD_BODY\":{\"USER_ID\":\"user123\",\"ORDER_ID\":\"order123\",\"ORDER_DT\":\"20191112145811\",\"TOTAL_AMT\":\"100.00\",\"PAY_AMT\":\"90.00\",\"DISCOUNT_AMT\":\"10.00\",\"ORDER_STATUS\":\"1\",\"REFUND_STATUS\":\"0\",\"MCT_NM\":\"XXX商户\"}}";

        /**
         * 加密及获取签名
         */
        // 公钥加密得到密文并使用base64处理
        String enc_msg = RSAUtil.encrypt(msg, publicKey);
        System.out.println(enc_msg);
        Base64.Encoder encoder = Base64.getEncoder();
        enc_msg = encoder.encodeToString(enc_msg.getBytes("UTF-8"));
        System.out.println(enc_msg);
        enc_msg = enc_msg.replaceAll("\r\n", "").replaceAll("\r", "").replaceAll("\n", "");
        System.out.println(enc_msg);


        // 根据源报文+私钥获得MD5签名
        String mac_info = MD5Util.getMD5(msg + privateKey);

        /**
         * 解密及验签
         */
        // base64逆处理并用私钥解密
        enc_msg = "UWl3VVVIT0IzSHp6VUtpNFVmb25VcWJjMnBKdU9IclJUZ3lISGJLR3Myd21saWQvMTVvenNMNk5xWmFwUzl1clh5K2VkVmJuU1BYMg0KTzUwamNkZWRmdjc5NHdDRmJSdjF4WDl4bzAwejMwU2k2NXJ6cTVaVVU4dUt2ZmNPeVJ1cDJkTC9SOUgvODVUblNLbEVXUnErSGo3dw0KMzB2YjFaeU1acU5iRVZnb25VSTUrcmlPV2wweWUwb2xQTVFoei9CVWhDcU9qOExqR21hTDBCdGpVbVdiTyttU3Vpa0s5Y25md3g0SQ0KV0xUSk1BWjl3OHdkZ0FqamI5bXhJbFJUM3JrU3VId1RMdGF0VkdJcGovVDAvdk5nQzNUcWgvODJOQnZvYXdoYnl0Z3AwRW9FNWp5bw0KdVhmYVZDZE9IeGp4ZkpyclFFSCt5THFoZXl2MEx2OGJ1b0x0N0pYMi9zM0pJS0J1bFdSZWJHRTMrcmpEMm9sUVJiYklONkdpeDlodQ0KUEprWkFkK0UrcTV1ZFR4OXpFRlJyWVBHVURzL0RLK0JFSk5iYWZGRnllZTBrRzh2YVlmU1NxeFBWcVBrblRzZ2oxdXFqME0xTGFCNQ0KZ1drVU9vVnl4bUtXUEpYd3JqYXlkSUxVeEZ2dkwzZEpHYmV6cnUwK3d1V3A2QXBQVnRkOElaSm4NCg==";
        Base64.Decoder decoder = Base64.getMimeDecoder();
        enc_msg = new String(decoder.decode(enc_msg), "UTF-8");
        System.out.println(enc_msg);
        String dec_msg = RSAUtil.decrypt(enc_msg, privateKey);
        System.out.println(dec_msg);

        // 验签
        String dec_mac = MD5Util.getMD5(dec_msg + privateKey);
        if (mac_info.equals(dec_mac)) {
            return "验签通过";
        } else {
             return "验签失败";
        }
    }

    @ResponseBody
    @RequestMapping("gpdf")
    public JsonData gpdf(@RequestBody JSONObject jsonParam) {
        //获取前端post过来的json数据
        String pdfPath = jsonParam.get("pdfPath").toString();
        String newPDFPath = jsonParam.get("newPDFPath").toString();
        String pdfHeight = jsonParam.get("pdfHeight").toString();
        String pdfWidth = jsonParam.get("pdfWidth").toString();
        String pwd = jsonParam.get("pwd").toString();
        String seal = jsonParam.get("seal").toString();
        String jsonString = jsonParam.get("signs").toString();

        List<Map<String, String>> list = new ArrayList<Map<String, String>>();

        JSONObject jsonObject = JSONObject.parseObject(jsonString);
//        LinkedHashMap signMap = (LinkedHashMap)jsonObject1;
        Iterator itSigns = jsonObject.entrySet().iterator();
        while (itSigns.hasNext()) {
            Map.Entry entrySigns = (Map.Entry) itSigns.next();
            JSONObject lhpSigns = (JSONObject)entrySigns.getValue();
            Iterator signs = lhpSigns.entrySet().iterator();
            while (signs.hasNext()) {
                Map.Entry sign = (Map.Entry) signs.next();
                Map signInfo = (Map) sign.getValue();
                Map<String, String> poi = new HashMap<String,String>();
                poi.put("pageNum", signInfo.get("pageNum").toString());
                poi.put("top", signInfo.get("top").toString());
                poi.put("left", signInfo.get("left").toString());
                poi.put("width", signInfo.get("width").toString());
                poi.put("height", signInfo.get("height").toString());
                poi.put("sealUrl", signInfo.get("sealUrl").toString());
                list.add(poi);
            }
        }

        if(Empty.isNull(pdfPath)) return JsonData.Error("参数不能为空");
        pdfPath = path + pdfPath.replace("./", "");
        newPDFPath = newPath + newPDFPath.replace("./", "");
        try {
            Pdf.generatePDF(pdfPath, newPDFPath, pdfHeight, pdfWidth, list, pwd, seal);
            return JsonData.success("处理成功");
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return JsonData.Error("处理失败");
        }
    }
}
